package com.uuah.server.component.model;

import java.lang.reflect.Method;

import com.uuah.server.api.component.model.IEntryPointResolver;
import com.uuah.server.config.i18n.ServerMessages;

public class InvocationResult {
	public static final int STATE_INVOKE_NOT_SUPPORTED = 0;

	public static final int STATE_INVOKED_SUCESSFUL = 1;

	public static final int STATE_INVOKED_FAILED = 2;

	private String errorMessage;

	private String methodCalled;

	private Object result;

	private int state;

	public InvocationResult(int state) {
		if (state < 0 || state > 2) {
			throw new IllegalArgumentException("state");
		}
		this.state = state;
	}

	public InvocationResult(Object result, Method method) {
		this.result = result;
		this.state = STATE_INVOKED_SUCESSFUL;
		this.methodCalled = method.getName();
	}

	public String getMethodCalled() {
		return methodCalled;
	}

	public Object getResult() {
		return result;
	}

	public int getState() {
		return state;
	}

	public void setErrorMessage(String message) {
		if (state == STATE_INVOKED_SUCESSFUL) {
			throw new IllegalStateException(ServerMessages
					.invocationSuccessfulCantSetError().toString());
		}
		errorMessage = message;
	}

	public boolean hasError() {
		return errorMessage != null;
	}

	public String getErrorMessage() {
		return errorMessage;
	}

	public void setErrorNoMatchingMethods(Object component, Class[] args,
			IEntryPointResolver resolver) {
		setErrorMessage(ServerMessages.noEntryPointFoundWithArgsUsingResolver(
				component.getClass().getName(), args, resolver).toString());
	}

	public void setErrorNoMatchingMethodsCalled(Object component,
			String methods, IEntryPointResolver resolver) {
		setErrorMessage(ServerMessages
				.noMatchingMethodsOnObjectCalledUsingResolver(
						component.getClass().getName(), methods, resolver)
				.toString());
	}
}
